<template>
    <view style="padding: 15px;">
        <u-form ref="validateFormRef" :model="validateForm.value" :label-width="150">
            <u-form-item label="商城名称" prop="name" required>
                <u-input v-model="validateForm.value.name" placeholder="请输入商城名称"/>
            </u-form-item>
            <u-form-item label="省市区" prop="region" required>
                <u-input type="select" :select-open="pickerShow" v-model="validateForm.value.region" placeholder="省市区县、乡镇等" @click="pickerShow = true"/>
            </u-form-item>
            <u-form-item label="地址" prop="address" required>
                <u-input type="textarea" height="40" placeholder="街道、楼牌等" v-model="validateForm.value.address"/>
            </u-form-item>
            <u-form-item label="邮箱" prop="email" required>
                <u-input v-model="validateForm.value.email" placeholder="请输入邮箱"/>
            </u-form-item>
            <u-form-item label="验证码" prop="identifyingCode" required>
                <u-input placeholder="请输入验证码" v-model="validateForm.value.identifyingCode" type="text"></u-input>
                <u-button slot="right" type="success" size="mini" @click="getCode">{{codeTips}}</u-button>
            </u-form-item>
            <u-form-item label="支付码" prop="payCode" required>
                <u-input placeholder="请输入验证码" v-model="validateForm.value.payCode" type="text"></u-input>
                <u-button slot="right" type="success" size="mini" @click="getPayCode">{{payCodeTips}}</u-button>
            </u-form-item>
            <u-form-item label="商城管理员登录账号" :label-width="300" prop="username" required>
                <u-input v-model="validateForm.value.username" placeholder="请输入商城管理员登录账号"/>
            </u-form-item>
            <u-form-item label="商城管理员登录密码" :label-width="300" prop="password" required>
                <u-input type="password" v-model="validateForm.value.password" placeholder="请输入商城管理员登录密码"/>
            </u-form-item>
            <u-form-item label="商城管理员确认密码" :label-width="300" prop="confirmPassword" required>
                <u-input type="password" v-model="validateForm.value.confirmPassword" placeholder="请输入商城管理员确认密码"/>
            </u-form-item>
        </u-form>

        <u-button type="error" @click="submit">提交</u-button>

        <!--选择省市区-->
        <u-picker mode="region" v-model="pickerShow" @confirm="regionConfirm" v-if="!validateForm.value.provinceName"></u-picker>
        <u-picker mode="region" v-model="pickerShow" @confirm="regionConfirm" v-if="validateForm.value.provinceName"
                  :default-region="[validateForm.value.provinceName, validateForm.value.cityName, validateForm.value.areaName]"></u-picker>

        <!--邮箱验证码-->
        <u-verification-code seconds="60" ref="uCode" @change="codeChange"></u-verification-code>

        <u-verification-code seconds="5" ref="uCodePayCode" @change="payCodeChange"></u-verification-code>
    </view>
</template>

<script>

    import {CommonService} from "../../../../../dev/services/common.service";
    import {CommonUtil} from "../../../../../dev/core/utils/common.util";
    import {TbCommunityService} from "../../../../../dev/services/tb-community.service";
    import {TbEmailIdentifyingCodeService} from "../../../../../dev/services/tb_email_identifying_code.service";
    import {UFormUtil} from "../../../../../dev/core/utils/u-form.util";
    import {TbEmailPayCodeOrderService} from "../../../../../dev/services/tb-email-pay-code-order.service";
    import {initPayEnvironment, pay_tbEmailPayCodeOrder} from "../../../../../dev/core/utils/pay";

    export default {
        data() {
            return {
                pickerShow: false,
                codeTips: '',  // 获取验证码提示语
                payCodeTips: '获取支付码',  // 获取支付码提示语
                validateForm: {
                    value: {
                        name: null,
                        region: '',
                        provinceName: '',
                        cityName: '',
                        areaName: '',
                        address: null,
                        email: '',
                        identifyingCode: '',
                        payCode: '',  // 支付码
                        status: '0',
                        username: '',
                        password: '',
                        confirmPassword: '',
                    },
                    rules: {
                        name: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']},
                            {
                                trigger: ['blur'],
                                asyncValidator: (rule, value, callback) => {
                                    if (this.validateForm.value.region) {
                                        new CommonService().uniqueCheckByFields({
                                            "tableName": "tb_community",
                                            "fieldList": [
                                                {"fieldName": "province_name", "fieldValue": this.validateForm.value.provinceName},
                                                {"fieldName": "city_name", "fieldValue": this.validateForm.value.cityName},
                                                {"fieldName": "area_name", "fieldValue": this.validateForm.value.areaName},
                                                {"fieldName": "name", "fieldValue": this.validateForm.value.name}
                                            ],
                                            "excludeId": null
                                        }).then(result => {
                                            if (result.status === "fail") {
                                                callback(new Error('该区域商城已存在！'));
                                            } else {
                                                callback()
                                            }
                                        });
                                    } else {
                                        callback()
                                    }
                                }
                            }
                        ],
                        region: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']},
                            {
                                trigger: ['change', 'blur'],
                                asyncValidator: (rule, value, callback) => {
                                    if (this.validateForm.value.name) {
                                        UFormUtil.validation(this.$refs.validateFormRef, 'name');
                                    }
                                    callback();
                                }
                            }
                        ],
                        address: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                        ],
                        email: [
                            {required: true, type: "email", message: '请输入有效的邮箱号码', trigger: ['change', 'blur']},
                        ],
                        identifyingCode: [
                            {required: true, message: '请输入邮箱验证码', trigger: ['change', 'blur']},
                            {
                                trigger: ['blur'],
                                asyncValidator: (rule, value, callback) => {
                                    new TbEmailIdentifyingCodeService().mailIdentifyingCodeCheck(this.validateForm.value.email, this.validateForm.value.identifyingCode).then(result => {
                                        if (result.status === "success") {
                                            callback()
                                        } else {
                                            callback(new Error(result.message));
                                        }
                                    });
                                }
                            }
                        ],
                        payCode: [
                            {required: true, message: '请输入支付码', trigger: ['change', 'blur']},
                            {
                                trigger: ['blur'],
                                asyncValidator: (rule, value, callback) => {
                                    new TbEmailIdentifyingCodeService().mailIdentifyingCodeCheck(this.validateForm.value.email, this.validateForm.value.identifyingCode).then(result => {
                                        if (result.status === "success") {
                                            callback()
                                        } else {
                                            callback(new Error(result.message));
                                        }
                                    });
                                }
                            }
                        ],
                        username: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']},
                            {
                                trigger: ['blur'],
                                asyncValidator: (rule, value, callback) => {
                                    new CommonService().uniqueCheckByFields({
                                        'tableName': 'sys_user',
                                        'fieldList': [
                                            {'fieldName': 'username', 'fieldValue': value}
                                        ],
                                        'excludeId': null
                                    }).then(result => {
                                        if (result.status === "fail") {
                                            callback(new Error('登录账号已存在！'));
                                        } else {
                                            callback();
                                        }
                                    });
                                }
                            }
                        ],
                        password: [
                            {required: true, message: '请输入登录密码!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '请输入登录密码!', trigger: ['change', 'blur']},
                            {
                                trigger: ['blur'],
                                asyncValidator: (rule, value, callback) => {
                                    if (this.validateForm.value.confirmPassword) {
                                        UFormUtil.validation(this.$refs.validateFormRef, 'confirmPassword');
                                    }
                                    callback();
                                }
                            }
                        ],
                        confirmPassword: [
                            {required: true, message: '请输入确认密码!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '请输入确认密码!', trigger: ['change', 'blur']},
                            {
                                trigger: ['blur'],
                                asyncValidator: (rule, value, callback) => {
                                    if (value !== this.validateForm.value.password) {
                                        callback(new Error('两次输入密码不一致！'))
                                    } else {
                                        callback();
                                    }
                                }
                            }
                        ],
                    }
                }
            }
        },
        onReady() {
            const _self = this
        },
        methods: {
            // 选择地区回调
            regionConfirm(e) {
                console.log(e);
                this.validateForm.value.region = e.province.label + '-' + e.city.label + '-' + e.area.label;
                this.validateForm.value.provinceName = e.province.label;
                this.validateForm.value.cityName = e.city.label;
                this.validateForm.value.areaName = e.area.label;
            },
            codeChange(text) {
                this.codeTips = text;
            },
            payCodeChange(text) {
                this.payCodeTips = text;
            },
            // 获取验证码
            getCode() {
                const _self = this;
                if (this.$refs.uCode.canGetCode) {
                    // 模拟向后端请求验证码
                    uni.showLoading({
                        title: '正在获取验证码',
                        mask: true
                    });

                    this.validateForm.value.email = CommonUtil.trim(this.validateForm.value.email);
                    if (!this.validateForm.value.email) {
                        this.$u.toast('请先输入邮箱');
                        return;
                    }

                    new TbEmailIdentifyingCodeService().sendMailIdentifyingCode(this.validateForm.value.email).then(result => {
                        CommonUtil.alert(result.message);
                        uni.hideLoading();
                        // 通知验证码组件内部开始倒计时
                        _self.$refs.uCode.start();
                    });
                } else {
                    this.$u.toast('倒计时结束后再发送');
                }
            },
            // 获取支付码
            getPayCode() {
                const _self = this;
                UFormUtil.validation(_self.$refs.validateFormRef, 'identifyingCode').then(isValid => {
                    console.log(isValid);
                    if (isValid) {
                        if (this.$refs.uCodePayCode.canGetCode) {
                            // 模拟向后端请求验证码
                            uni.showLoading({
                                title: '正在获取支付码',
                                mask: true
                            });

                            new TbEmailPayCodeOrderService().sendPayCode({
                                email: _self.validateForm.value.email,
                                type: "0"
                            }).then(result => {
                                if (result.status === "success") {
                                    CommonUtil.alert(result.message);
                                } else {
                                    if (result.data === "0") {  // 没有支付码，需要支付
                                        initPayEnvironment().then(result => {
                                            pay_tbEmailPayCodeOrder({
                                                email: _self.validateForm.value.email,
                                                type: "0",
                                                callback: function (payResult) {
                                                    if (payResult) {
                                                        _self.getPayCode();
                                                    }
                                                }
                                            })
                                        });
                                    } else if (result.data === "1") {  // 存在支付码，发送失败
                                        CommonUtil.alert(result.message);
                                    }
                                }

                                uni.hideLoading();
                                // 通知验证码组件内部开始倒计时
                                _self.$refs.uCodePayCode.start();
                            });
                        } else {
                            this.$u.toast('倒计时结束后再获取');
                        }
                    }
                });
            },
            submit() {
                const _self = this;
                this.$refs.validateFormRef.validate(valid => {
                    if (valid) {
                        console.log('验证通过', _self.validateForm.value);
                        CommonUtil.alert({
                            title: '提示！',
                            content: '确认提交吗？',
                            showCancel: true, // 是否显示取消按钮
                            success: function (res) {
                                if (res.cancel) { // 点击取消,默认隐藏弹框
                                } else { // 点击确定
                                    new TbCommunityService().openNewTbCommunity(_self.validateForm.value).then(result => {
                                        CommonUtil.alertNavigateBack(result.message);
                                    });
                                }
                            }
                        });
                    } else {
                        console.log('验证失败');
                    }
                });
            }
        }
    }
</script>

<style lang="scss" scoped>
</style>
